package com.mindskip.xzs.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mindskip.xzs.domain.Klass;
import com.mindskip.xzs.domain.KlassUser;
import com.mindskip.xzs.repository.KlassMapper;
import com.mindskip.xzs.repository.KlassUserMapper;
import com.mindskip.xzs.service.KlassService;
import com.mindskip.xzs.utility.PageInfoHelper;
import com.mindskip.xzs.viewmodel.admin.klass.KlassPageRequestVM;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class KlassServiceImpl extends BaseServiceImpl<Klass> implements KlassService {
    private final KlassMapper klassMapper;
    @Autowired
    private KlassUserMapper klassUserMapper;

    public KlassServiceImpl(KlassMapper klassMapper) {
        super(klassMapper);
        this.klassMapper = klassMapper;
    }

    @Override
    public List<Klass> allKlass() {
        return klassMapper.allKlass();
    }

    @Override
    public PageInfo<Klass> page(KlassPageRequestVM model) {
        if (model.getTeacherId()!=null && model.getTeacherId()!=""){
            List<KlassUser> klassUsers = klassUserMapper.selectByUserId(Integer.valueOf(model.getTeacherId()));
            List<Integer> ids = new ArrayList<>();
            for (KlassUser klassUser : klassUsers) {
                ids.add(klassUser.getUserId());
            }
            model.setTeacherClass(ids);
        }
        PageInfo<Klass> idDesc = PageHelper.startPage(model.getPageIndex(), model.getPageSize(), "id desc").doSelectPageInfo(() ->
                klassMapper.page(model)
        );

        return idDesc;
    }

    @Override
    public void addKlass(Integer id, String token) {

        Klass klass = klassMapper.selectByToken(token);
        if (!ObjectUtils.isEmpty(klass)){
            Integer num = klass.getNum();
            klass.setNum(num+1);
            klassMapper.updateByPrimaryKey(klass);
            KlassUser klassUser = new KlassUser();
            klassUser.setUserId(id);
            klassUser.setKlassId(klass.getId());
            klassUserMapper.insert(klassUser);
        }

    }

    @Override
    public int insert(Klass klass) {
        klass.setCountersign(UUID.randomUUID().toString());
        return super.insert(klass);
    }

    @Override
    public int deleteById(Integer id) {
        Klass klass = selectById(id);
        if (klass == null) {
            // 可以根据实际需求进行适当的错误处理，例如抛出异常或返回错误响应
            throw new IllegalArgumentException("指定的班级不存在");
        }
        klass.setDeleted(true);
        return updateById(klass);
    }

}
